﻿using CheckIn;
using COSXML;
using COSXML.Auth;
using COSXML.Model.Object;
using JMS;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UploadWeb.Dtos;
using Way.Lib;

namespace UploadWeb.Controllers
{
    [Microsoft.AspNetCore.Authorization.Authorize]
    [ApiController]
    [Route("[controller]/[action]")]
    public class MainController : ControllerBase
    {
        private readonly ILogger<MainController> _logger;
        const string NotifyToken = "B7467gqt0YCJbXh8Ddh";

        public MainController(ILogger<MainController> logger)
        {
            _logger = logger;
        }

        static string GetSHA1HashData(string data)
        {
            // 将字符串转换为字节序列
            byte[] bytes = Encoding.UTF8.GetBytes(data);

            // 创建一个 SHA1 对象
            SHA1 sha1 = SHA1.Create();

            // 计算哈希值
            byte[] hashBytes = sha1.ComputeHash(bytes);

            // 将哈希值转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString().ToLower();
        }

        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        [HttpGet]
        [HttpPost]
        public async Task<string> Notify(string? echostr, string? timestamp, string? nonce,string? signature)
        {
            string postBody = null;
            _logger.LogDebug($"收到{Request.Method} - {Request.GetDisplayUrl()}");
            try
            {
                if (Request.Method == "POST"  )
                {
                    if (Request.ContentLength != null && Request.ContentLength > 0)
                    {
                        var postContent = new byte[(int)Request.ContentLength];
                        await Request.Body.ReadAsync(postContent, 0, postContent.Length);
                        postBody = Encoding.UTF8.GetString(postContent);
                        _logger.LogDebug($"post body:{postBody}");
                    }
                    else
                    {
                        foreach (var item in Request.Form)
                        {
                            _logger.LogDebug($"{item.Key}:{item.Value}");
                        }
                    }
                }

            }
            catch
            {

            }
            try
            {
                string[] arr = new string[] { timestamp, nonce, NotifyToken };
                arr = arr.OrderBy(m => m).ToArray();

                var toSign = string.Join("", arr);

                _logger.LogDebug($"验证字符串：{toSign}");

                var mySignRet = GetSHA1HashData($"{toSign}");
                _logger.LogDebug($"签名结果：{mySignRet}");

                if (mySignRet == signature)
                {
                    _logger.LogDebug($"签名一致");
                    //签名一致
                    if (postBody != null)
                    {
                        var weChatNotifyModel = postBody.FromJson<WeChatNotifyModel>();
                        if(weChatNotifyModel.Event == "wxa_media_check")
                        {
                            using var rc = new RemoteClient(Global.GatewayAddresses);
                            var accountAdminService = await rc.GetMicroServiceAsync("AccountAdminService");
                            try
                            {                             
                                await accountAdminService.InvokeAsync("NotifyImageCheckResult", weChatNotifyModel.trace_id, weChatNotifyModel.result);
                                _logger.LogDebug($"成功通知AccountAdminService");
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex, "");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex , "");
            }

            return echostr;
        }

        [RequestSizeLimit(10 * 1024 * 1024)]
        [HttpPost]
        public async Task<List<string>> UploadForm()
        {
            var qCloudConfig = Program.OssConfig.Current;
            List<string> urls = new List<string>();

            CosXmlConfig config = new CosXmlConfig.Builder()
            .IsHttps(false)
           .SetRegion(qCloudConfig.Region) // 设置COS服务区域，例如 ap-beijing
           .Build();

            QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(
                qCloudConfig.AccessKeyId,
                qCloudConfig.AccessKeySecret,
                300 // Token 的有效时间，单位为秒
            );

            // 初始化CosXml实例
            CosXml cosXml = new CosXmlServer(config, cosCredentialProvider);

            foreach (var file in Request.Form.Files)
            {
                using var ms = file.OpenReadStream();
                var ext = Path.GetExtension(file.FileName);

                var key = $"{qCloudConfig.Folder}/{Guid.NewGuid().ToString("N")}{ext}";


                // 上传文件
                PutObjectRequest request = new PutObjectRequest(qCloudConfig.BucketName, key, ms);

                // 执行请求
                PutObjectResult result = cosXml.PutObject(request);

                if (result.IsSuccessful() == false)
                    throw new InvalidOperationException($"上传失败，{result.httpMessage}");

                urls.Add(cosXml.GetObjectUrl(qCloudConfig.BucketName, key).Replace("http://", "https://"));
            }


            return urls;

        }
    }
}
